﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Xml;

using Microsoft.Samples.Office.UnifiedCommunications.Gadget.Config;

namespace Microsoft.Samples.Office.UnifiedCommunications.Gadget.EWSUtility
{
    public class EWSContact
    {
        public delegate IDictionary<string, ContactMessage> GetEmailCountsDelegate(EWSRequest ewsRequest, string myDisplayName);
        public delegate void ProcessEmailCountsDelegate(IDictionary<string, ContactMessage> contactCounts);

        public static IDictionary<string, ContactMessage> GetEmailCountTodayByContact(EWSRequest ewsRequest, string myDisplayName)
        {
            Dictionary<string, ContactMessage> contactEmails = new Dictionary<string, ContactMessage>();

            string baseQueryPath = "/m:FindItemResponse/m:ResponseMessages/m:FindItemResponseMessage";

            XmlDocument vmXmlDoc = ewsRequest.GetFolderCountTodayByContact(
                new EWSEnums.DistinguishedFolderId[] { 
                        EWSEnums.DistinguishedFolderId.inbox , 
                        EWSEnums.DistinguishedFolderId.sentitems,
                        EWSEnums.DistinguishedFolderId.deleteditems},
                    EWSEnums.BaseShape.AllProperties,
                    "From");

            XmlNamespaceManager xmlNamespaceManager = EWSRequest.CreateRequestXmlNamespaceManager(vmXmlDoc);
            
            XmlNode nodeFindItemResponseMessage = vmXmlDoc.DocumentElement.SelectSingleNode(
                EWSRequest.PrefixXPath(baseQueryPath),
                xmlNamespaceManager);

            string responseClass = nodeFindItemResponseMessage.Attributes["ResponseClass"].Value;

            if (responseClass.ToUpper() == "SUCCESS") // Return an empty list if error occured
            {
                // Returned Xml will contain both received and sent items, need to process differently
                //
                
                // Process Received
                //
                string senderPath = baseQueryPath + "/m:RootFolder/t:Items/t:Message/t:Sender/t:Mailbox/t:Name";
                XmlNodeList nodes = vmXmlDoc.SelectNodes(EWSRequest.PrefixXPath(senderPath), xmlNamespaceManager);
                foreach (XmlNode node in nodes)
                {
                    string from = default(string);
                    DateTime asOfTime = DateTime.Now;
                    from = node.InnerText;

                    if (from != myDisplayName)
                    {
                        if (contactEmails.ContainsKey(from))
                        {
                            ContactMessage curMessage = contactEmails[from];
                            curMessage.count += 1;
                            contactEmails[from] = curMessage;
                        }
                        else
                        {
                            contactEmails.Add(from, new ContactMessage(from, asOfTime, 1));
                        }
                    }
                }

                // Process Sent
                //
                string recipientPath = baseQueryPath + "/m:RootFolder/t:Items/t:Message/t:DisplayTo";
                nodes = vmXmlDoc.SelectNodes(EWSRequest.PrefixXPath(recipientPath), xmlNamespaceManager);
                foreach (XmlNode node in nodes)
                {
                    string to = default(string);
                    DateTime asOfTime = DateTime.Now;
                    to = node.InnerText;

                    if (to != myDisplayName)
                    {
                        if (to.IndexOf(";") >= 0) // Multiple recipients
                        {
                            string[] recipients = to.Split(';');

                            for (int i = 0; i < recipients.GetUpperBound(0); i++)
                            {
                                string recipient = recipients[i];

                                if (contactEmails.ContainsKey(recipient))
                                {
                                    ContactMessage curMessage = contactEmails[recipient];
                                    curMessage.count += 1;
                                    contactEmails[recipient] = curMessage;
                                }
                                else
                                {
                                    contactEmails.Add(recipient, new ContactMessage(recipient, asOfTime, 1));
                                }
                            }
                        }
                        else
                        {
                            if (contactEmails.ContainsKey(to))
                            {
                                ContactMessage curMessage = contactEmails[to];
                                curMessage.count += 1;
                                contactEmails[to] = curMessage;
                            }
                            else
                            {
                                contactEmails.Add(to, new ContactMessage(to, asOfTime, 1));
                            }
                        }
                    }
                }

                return contactEmails;
            }
            else
            {
                return null;
            }

        }

        public static void ProcessEmailCounts(IDictionary<string, ContactMessage> contactCounts)
        {
            try
            {
                ContactElementCollection currentContacts = GadgetConfigurationManager.GetCurrentContactList();
                GadgetConfigurationManager.ProcessContactUpdates(currentContacts, contactCounts);
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }

        public static string ResolveSIPAddress(EWSRequest ewsRequest, string primarySMTP)
        {
            string sipAddress = default(string);

            try
            {
                StringBuilder request = new StringBuilder();
                request.AppendLine("<ResolveNames ReturnFullContactData=\"true\">");
                request.AppendLine("    <UnresolvedEntry>");
                request.AppendLine(primarySMTP);
                request.AppendLine("    </UnresolvedEntry>");
                request.AppendLine("</ResolveNames>");

                EWSRequest requestResolveNames = new EWSRequest(ewsRequest.url,
                    ewsRequest.userName, ewsRequest.password, ewsRequest.domain, request.ToString());

                XmlDocument namesXmlDoc = requestResolveNames.MakeRawSoapRequest();
            }
            catch (Exception)
            {

                throw;
            }


            return sipAddress;
        }
    }
}
